﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Brain.Editor;
using System.Reflection;

namespace Brain
{
    public class DatabaseManager : IBrainSerialiable
    {
        public List<Type> DatabaseTypes { get; set; }

        public List<Database> Databases { get; set; }

        public DatabaseManager()
        {
            DatabaseTypes = new List<Type>();
        }

        public void FinishedInsertingTypes()
        {
            // ONLY create Types if they weren't loaded by a Plugin(loaded directly
            // from the Database file
            if (Databases == null)
            {
                Databases = new List<Database>();
                for (int i = 0; i < DatabaseTypes.Count; i++)
                {
                    Type t = DatabaseTypes[i];
                    Databases.Add((Database)Activator.CreateInstance(t));
                }
            }
        }
        
        public SerializationData Data { get; set; }

        public void SerializeData(DefaultSerializationManager manager)
        {
            Data = new SerializationData();
            Data.AddData("Data.Count", this.Databases.Count);
            for (int i = 0; i < Databases.Count; i++)
            {
                Database data = Databases[i];
                data.SerializeData(this.Data, i);
            }
            for (int i = 0; i < DatabaseTypes.Count; i++)
            {
                Type t = DatabaseTypes[i];
                Data.AddData("Data.Type", t.FullName);
                Data.AddData("Data.Assembly", t.Assembly.FullName);
            }
        }

        public void DeserializeData(DefaultSerializationManager manager, SerializationData newData)
        {
            int count = newData.GetData<int>("Data.Count");

            this.Databases = new List<Database>();
            this.DatabaseTypes = new List<Type>();
            for (int i = 0; i < count; i++)
            {
                string type = newData.GetData<string>("Data.Type");
                string ass = newData.GetData<string>("Data.Assembly");
                Assembly asse = Assembly.Load(ass);
                Type t = asse.GetType(type);
                Database data = (Database)Activator.CreateInstance(t);
                data.DeserializeData(newData, i);

                this.DatabaseTypes.Add(t);
                this.Databases.Add(data);
            }
        }
    }
}
